<template>
  <div class="stock-analysis-chart">
    <h3>股票走势分析</h3>
    
    <!-- 股票搜索栏 -->
    <div class="stock-search">
      <input v-model="searchQuery" placeholder="搜索股票代码或名称" @keyup.enter="searchStock" />
      <button @click="searchStock">搜索</button>
      <div v-if="searchResults.length > 0" class="search-results">
        <div 
          v-for="result in searchResults" 
          :key="result.code" 
          class="search-result-item"
          @click="selectStock(result)"
        >
          {{ result.name }} ({{ result.code }})
        </div>
      </div>
    </div>
    
    <div class="chart-container">
      <!-- 这里使用模拟数据展示股票走势图 -->
      <div class="stock-data">
        <div class="stock-header">
          <div class="stock-name">{{ stock.name }} ({{ stock.code }})</div>
          <div class="stock-price">
            <span class="current-price">{{ stock.currentPrice }}</span>
            <span class="price-change" :class="stock.changePercent >= 0 ? 'up' : 'down'">
              {{ stock.change }} ({{ stock.changePercent }}%)
            </span>
          </div>
        </div>
        <div class="chart-placeholder">
          <div class="chart-bar" v-for="(day, index) in stock.historyData" :key="index" 
               :style="{ height: getBarHeight(day.close), backgroundColor: getBarColor(day) }"></div>
        </div>
        <div class="stock-metrics">
          <div class="metric">
            <span class="label">开盘价:</span>
            <span class="value">{{ stock.openPrice }}</span>
          </div>
          <div class="metric">
            <span class="label">最高价:</span>
            <span class="value">{{ stock.highPrice }}</span>
          </div>
          <div class="metric">
            <span class="label">最低价:</span>
            <span class="value">{{ stock.lowPrice }}</span>
          </div>
          <div class="metric">
            <span class="label">成交量:</span>
            <span class="value">{{ formatVolume(stock.volume) }}</span>
          </div>
        </div>
        
        <!-- 智能分析功能 -->
        <div class="quick-actions">
          <h4>智能分析</h4>
          <div class="action-buttons">
            <button @click="analyzeTrend">分析趋势</button>
            <button @click="compareStocks">对比股票</button>
            <button @click="showNews">相关新闻</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

interface StockData {
  name: string;
  code: string;
  currentPrice: number;
  openPrice: number;
  highPrice: number;
  lowPrice: number;
  change: number;
  changePercent: number;
  volume: number;
  historyData: { date: string; open: number; close: number; high: number; low: number; volume: number }[];
}

interface SearchResultStock {
  code: string;
  name: string;
}

const stock = ref<StockData>({
  name: '上证指数',
  code: '000001',
  currentPrice: 3058.74,
  openPrice: 3045.21,
  highPrice: 3068.35,
  lowPrice: 3040.12,
  change: 13.53,
  changePercent: 0.44,
  volume: 2875640000,
  historyData: []
});

const searchQuery = ref('');
const searchResults = ref<SearchResultStock[]>([]);

// 模拟股票数据库
const mockStockDatabase: SearchResultStock[] = [
  { code: '000001', name: '上证指数' },
  { code: '000002', name: '万科A' },
  { code: '000858', name: '五粮液' },
  { code: '002415', name: '海康威视' },
  { code: '300750', name: '宁德时代' },
  { code: '600519', name: '贵州茅台' },
  { code: '600036', name: '招商银行' },
  { code: '601318', name: '中国平安' },
];

// 生成模拟历史数据
const generateHistoryData = () => {
  const data = [];
  const today = new Date();
  let basePrice = 3000;
  
  for (let i = 29; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(date.getDate() - i);
    
    const randomChange = (Math.random() - 0.5) * 20;
    const open = basePrice;
    const close = basePrice + randomChange;
    const high = Math.max(open, close) + Math.random() * 10;
    const low = Math.min(open, close) - Math.random() * 10;
    const volume = Math.floor(Math.random() * 2000000000) + 1000000000;
    
    data.push({
      date: date.toLocaleDateString(),
      open: Number(open.toFixed(2)),
      close: Number(close.toFixed(2)),
      high: Number(high.toFixed(2)),
      low: Number(low.toFixed(2)),
      volume
    });
    
    basePrice = close;
  }
  
  return data;
};

const getBarHeight = (price: number) => {
  // 简化的高度计算，实际应用中应使用更复杂的比例计算
  const minPrice = Math.min(...stock.value.historyData.map(d => d.close));
  const maxPrice = Math.max(...stock.value.historyData.map(d => d.close));
  const range = maxPrice - minPrice;
  return `${((price - minPrice) / range) * 100}%`;
};

const getBarColor = (dayData: any) => {
  return dayData.close >= dayData.open ? '#e74c3c' : '#2ecc71';
};

const formatVolume = (volume: number) => {
  if (volume >= 100000000) {
    return (volume / 100000000).toFixed(2) + '亿';
  } else if (volume >= 10000) {
    return (volume / 10000).toFixed(2) + '万';
  }
  return volume.toString();
};

// 搜索股票
const searchStock = () => {
  if (!searchQuery.value.trim()) {
    searchResults.value = [];
    return;
  }
  
  // 过滤匹配的股票
  searchResults.value = mockStockDatabase.filter(item => 
    item.code.includes(searchQuery.value) || 
    item.name.includes(searchQuery.value)
  );
};

// 选择股票
const selectStock = (selectedStock: SearchResultStock) => {
  stock.value.name = selectedStock.name;
  stock.value.code = selectedStock.code;
  searchQuery.value = '';
  searchResults.value = [];
  
  // 模拟加载新股票数据
  loadStockData(selectedStock.code);
};

// 加载股票数据
const loadStockData = (code: string) => {
  // 在实际应用中，这里应该使用code参数调用API获取真实数据
  // 模拟环境下，我们基于code做简单处理来使不同股票数据有所区别
  const seed = code.split('').reduce((sum, char) => sum + char.charCodeAt(0), 0) / 1000;
  stock.value.currentPrice = Number((Math.random() * 5000 + 100 + seed * 100).toFixed(2));
  stock.value.openPrice = Number((stock.value.currentPrice * (0.95 + Math.random() * 0.1)).toFixed(2));
  stock.value.highPrice = Number((Math.max(stock.value.currentPrice, stock.value.openPrice) * (1 + Math.random() * 0.05)).toFixed(2));
  stock.value.lowPrice = Number((Math.min(stock.value.currentPrice, stock.value.openPrice) * (1 - Math.random() * 0.05)).toFixed(2));
  stock.value.change = Number((stock.value.currentPrice - stock.value.openPrice).toFixed(2));
  stock.value.changePercent = Number(((stock.value.change / stock.value.openPrice) * 100).toFixed(2));
  stock.value.volume = Math.floor(Math.random() * 10000000000);
  
  // 重新生成历史数据
  stock.value.historyData = generateHistoryData();
};

// 智能分析功能
const analyzeTrend = () => {
  alert(`正在分析 ${stock.value.name}(${stock.value.code}) 的趋势，请稍候...`);
};

const compareStocks = () => {
  alert(`请选择要与 ${stock.value.name} 进行对比的股票`);
};

const showNews = () => {
  alert(`正在加载 ${stock.value.name} 的相关新闻...`);
};

onMounted(() => {
  stock.value.historyData = generateHistoryData();
});
</script>

<style scoped>
.stock-analysis-chart {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  position: relative;
}

h3 {
  margin: 0 0 16px 0;
  color: #2c3e50;
  font-size: 18px;
}

/* 股票搜索样式 */
.stock-search {
  margin-bottom: 16px;
  position: relative;
}

.stock-search input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 300px;
  margin-right: 8px;
}

.stock-search button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.stock-search button:hover {
  background-color: #2980b9;
}

.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 200px;
  overflow-y: auto;
  z-index: 10;
  width: 300px;
  margin-top: 4px;
}

.search-result-item {
  padding: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-result-item:hover {
  background-color: #f5f8ff;
}

.stock-data {
  width: 100%;
}

.stock-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.stock-name {
  font-size: 20px;
  font-weight: bold;
  color: #2c3e50;
}

.stock-price {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.current-price {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.price-change {
  font-size: 16px;
}

.price-change.up {
  color: #e74c3c;
}

.price-change.down {
  color: #2ecc71;
}

.chart-placeholder {
  display: flex;
  align-items: flex-end;
  height: 200px;
  gap: 4px;
  margin: 20px 0;
  padding: 0 10px;
}

.chart-bar {
  flex: 1;
  min-width: 4px;
  border-radius: 2px 2px 0 0;
  transition: height 0.3s ease;
}

.stock-metrics {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

.metric {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric .label {
  font-size: 14px;
  color: #7f8c8d;
}

.metric .value {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

/* 智能分析按钮区域 */
.quick-actions {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

.quick-actions h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #2c3e50;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.action-buttons button:first-child {
  background-color: #3498db;
  color: white;
  border-color: #3498db;
}

.action-buttons button:hover {
  background-color: #f5f5f5;
}

.action-buttons button:first-child:hover {
  background-color: #2980b9;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stock-search input {
    width: 100%;
    margin-bottom: 8px;
  }
  
  .search-results {
    width: 100%;
  }
  
  .stock-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .stock-metrics {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .metric {
    flex: 1 1 calc(50% - 10px);
    min-width: 140px;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
}
</style>